<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Crypt;
use DB;
class UserController extends Controller
{
    public function __construct()
    {
      $this -> middleware('login');
    }
    //add
    public function add()
    {
    	return view('admin.user.add',['title' => '用户添加']);
    }

    public function insert(Request $request)
    {
            $this -> validate($request,[
            'name' => 'min:6|max:18',
            'password' => 'min:6|max:18',
            'repassword' => 'same:password',
            'email' => 'email',
            'phone' => 'digits:11'
            ],[
            'name.min' => '用户名最少6位',
            'name.max' => '用户名最多18位',
            'password.min' => '密码最少6位',
            'password.max' => '密码最多18位',
            'repassword.same' => '确认密码不一致',
            'email.email' => '请输入正确的邮箱格式',
            'phone.digits' => '请输入11位数字是手机号'
            ]);
            $data = $request -> except('_token');
            $userData['name'] = $data['name'];
            $userData['password'] = $data['password'];
            $userData['email'] = $data['email'];
            $userData['phone'] = $data['phone'];
            $userData['airline'] = 0;
            $userData['token'] = str_random(50);
            $userData['password']   =  Crypt::encryptString('password');
            $time = Date('Y-m-d H-i-s');
            $userData['created_at'] = $time;
            $userData['updated_at'] = $time;
            $userInfo['created_at'] = $time;
            $userInfo['updated_at'] = $time;
            $userInfo['pic'] = '/uploads/avatar/default.jpg';
            // DB::transaction(function ($userData) {
            //     dd($userData);
            //     $userInfo['user_id'] = DB::table('users')->insertGetId($userData);

            //     DB::table('users_info')->insert($userInfo);
            // });
            DB::beginTransaction();
            $userInfo['user_id'] = DB::table('users')->insertGetId($userData);
            if($userInfo['user_id']  >0 )
            {
                $res  = DB::table('users_info')->insert($userInfo);
                if($res)
                {
                   DB::commit();
                   return redirect('admin/user/index') -> with(['info' => '添加成功']);
                }else{
                   DB::rollback();
                   return back() -> with(['info' => '添加失败']);
                }
            }else
            {
                DB::rollback();
                return back() -> with(['info' => '添加失败']);
            }
    }


    public function index(Request $request)
    {
          $num = $request -> input('num',10);
          $keywords = $request -> input('keywords','');
          $data = DB::table('users') -> where('name','like','%'.$keywords.'%') -> paginate($num) ;
          // dd($data);
          return view('admin.user.index',['data' => $data ,'request' => $request -> all(), 'title' => '用户列表']);
    }



    //当inp失去焦点发送ajax触发的方法
    public function changeName(Request $request)//ajax data发送的值会自动存入request
    {
        $id = $request -> id;
        $name = $request -> name;

        //根据传过来的参数去修改为此ID的name值
       $res = DB::table('users') -> where('id',$id) -> update(['name' => $name]);

       //判断是否修改成功
       if($res)
       {
        return 1;
       }else
       {
        return 0;
       }
    }
    //

    //状态改变
    public function changeAirline(Request $request)
    {
        $arr = ['禁用' => '0','启用' => '1'];
        $id = $request -> id;
        $airline = $arr[$request -> airline];
        if($airline == 0)
        {
            $airline = 1;

        }else
        {
            $airline = 0;
        }
        
        $res = DB::table('users') -> where('id',$id) -> update(['airline' => $airline]);

       //判断是否修改成功

       if($res)
       {
        // retrun $res;
        return $airline;
       }
    }//


    //编辑
    public function edit($id)
    {
      $data = DB::table('users')
          ->  select('users.*','users_info.pic')
          -> leftJoin('users_info','users.id','=','users_info.user_id')
          -> where('users.id','=',$id) 
          -> first();
        // dd($data);
      return view('admin.user.edit',['title' => '用户编辑', 'data' => $data]);
      
    }

    public function update(Request $request)
    {
        // dd($request);
        $this -> validate($request,[
            'name' => 'min:6|max:18',
            'email' => 'email',
            'phone' => 'digits:11',
            'pic' => 'image|max:2048',
            ],[
            'name.min' => '用户名最少6位',
            'name.max' => '用户名最多18位',
            'email.email' => '请输入正确的邮箱格式',
            'phone.digits' => '请输入11位数字是手机号',
            'pic.image' => '你必须传一张图片',
            'pic.max' => '最大2M' 
            ]);

        $id = $request -> id;
        // $pic = $request -> file('pic');
        $data = $request -> except('_token','id','pic');
        // dd($data);
        // dd($request);
        $ispic = '';
         if($request -> hasFile('pic'))
         {

            if($request -> file('pic') -> isValid())
            {
              //处理头像
              //获取文件后缀
              $extension = $request -> file('pic') -> getClientOriginalExtension();

              $filename = mt_rand(100000,999999999).'.'.$extension;

              $dir = './uploads/avatar/';

              $request -> file('pic') -> move($dir, $filename);

              $userInfoData['pic'] = '/uploads/avatar/'.$filename;
              // dd($userInfoData['pic']);
              //获取原来的图片
              $oldPic = DB::table('users_info') -> where('user_id',$id) -> first() -> pic;

              //判断是不是默认值
              if(!empty($oldPic))
              {
                  if($oldPic != '/uploads/avatar/default.jpg')
                 {
                      if(file_exists('.'.$oldPic))
                      {
                        unlink('.'.$oldPic);
                      }
                    
                  }
              }

              $ispic = DB::table('users_info') -> where('user_id',$id) -> update($userInfoData);
            
            }
          
         }else
         {
          $userInfoData['pic'] = '/uploads/avatar/default.jpg';
         }
         $res = DB::table('users') -> where('id',$id) -> update($data);

         if($res || $ispic)
         {
          return redirect('/admin/user/index') -> with(['info' => '修改成功']);
         }else
         {
          return back() -> with(['info' => '修改失败']);
         }
    }


    //删除
    public function delete($id)
    {
        $oldPic = DB::table('users_info') -> where('id',$id) -> first() -> pic;

        $res = DB::table('users') -> where('id',$id) -> delete();

        if($res)
        {
          DB::table('users_info') -> where('user_id', $id) -> delete();
            if(!empty($oldPic))
              {
                  
                  if($oldPic != '/uploads/avatar/default.jpg')
                 {
                      if(file_exists('.'.$oldPic))
                      {
                        unlink('.'.$oldPic);
                      }
                    
                 }
              }
         }   

      if($res)
         {
          return redirect('/admin/user/index') -> with(['info' => '删除成功']);
         }else
         {
          return back() -> with(['info' => '删除失败']);
         }
    }

    

}
